#include"SList.h"
void SLPrint(SL* phead)
{
	SLNode* cur = phead;
	while (cur)
	{
		printf("%d->", cur->x);
		cur = cur->next;
	}
	printf("NULL\n");
}
SLNode* STByNode(SLDataType x)
{
	SLNode* newnode = (SLNode*)malloc(sizeof(SLNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	newnode->next = NULL;
	newnode->x = x;
	return newnode;
}
void SLPushBack(SL** pphead, SLDataType x)
{
	assert(pphead);
	SLNode* newnode = STByNode(x);
	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	else
	{
		SLNode* cur = *pphead;
		while (cur->next)
		{
			cur = cur->next;
		}
		cur->next = newnode;
	}
}
void SLPushFront(SL** pphead, SLDataType x)
{
	assert(pphead);
	SLNode* newnode = STByNode(x);
	newnode->next = *pphead;
	*pphead = newnode;
}
void SLPopBack(SL** pphead)
{
	assert(pphead && *pphead);
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLNode* prev = NULL;
		SLNode* cur = *pphead;
		while (cur->next)
		{
			prev = cur;
			cur = cur->next;
		}
		free(cur);
		cur = NULL;
		prev->next = NULL;
	}
}
void SLPopFront(SL** pphead)
{
	assert(pphead && *pphead);
	SLNode* prev = *pphead;
	*pphead = (*pphead)->next;
	free(prev);
	prev = NULL;
}
SLNode* SLFind(SL* phead, SLDataType x)
{
	assert(phead);
	SLNode* cur = phead;
	while (cur)
	{
		if (cur->x == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}
void SLInsert(SL** pphead, SL* pos, SLDataType x)
{
	assert(pphead);
	assert(pos);
	SLNode* newnode = STByNode(x);
	if (*pphead == NULL)
	{
		SLPushFront(pphead, x);
	}
	else
	{
		SLNode* cur = *pphead;
		while (cur->next != pos)
		{
			cur = cur->next;
		}
		cur->next = newnode;
		newnode->next = pos;
	}
}
void SLInsertAfter(SL* pos, SLDataType x)
{
	assert(pos);
	SLNode* newnode = STByNode(x);
	newnode->next = pos->next;
	pos->next = newnode;

}
void SLEarse(SL** pphead, SL* pos)
{
	assert(pphead && *pphead);
	assert(pos);
	if (pos == *pphead)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLNode* cur = *pphead;
		while (cur->next != pos)
		{
			cur = cur->next;
		}
		cur->next = pos->next;
		free(pos);
		pos = NULL;
	}
}
void SLEarseAfter(SL** pphead, SL* pos)
{
	assert(pphead && *pphead);
	assert(pos);
	assert((*pphead)->next);
	SLNode* cur = *pphead;
	SLNode* prev = pos->next;
	pos->next = prev->next;
	free(prev);
	prev = NULL;
}